package com.ncmmall.application.business.goods;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.feijin.commons.lang.ArithUtils;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.GoodsRepository;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsAttributeRepository;
import com.ncmmall.domain.business.goods.attribute.GoodsSaleAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsSaleAttributeRepository;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.business.goods.image.GoodsImage;
import com.ncmmall.domain.business.goods.image.GoodsImageRepository;
import com.ncmmall.domain.business.goods.params.GoodsParams;
import com.ncmmall.domain.business.goods.params.GoodsParamsRepository;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.goods.sku.GoodsSkuRepository;
import com.ncmmall.domain.business.goods.sku.QGoodsSku;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品管理
 *
 * @author linxs
 * @date 2019-07-10 21:11
 */
@Service
@Transactional
public class GoodsApplication {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsSkuRepository skuRepository;

    @Autowired
    private GoodsParamsRepository paramsRepository;

    @Autowired
    private GoodsImageRepository imageRepository;

    @Autowired
    private GoodsSaleAttributeRepository saleAttributeRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsAttributeRepository attributeRepository;

    @Autowired
    private WebUserRepository userRepository;

    public double getSupplierLeverPrice(GoodsSku sku, int quantity) {

        if (sku.getSkuLever5Count() <= quantity && sku.getSkuLever5Count() != 0 && sku.getSkuLever5Price() != 0) {
            return sku.getSkuLever5Price();
        }

        if (sku.getSkuLever4Count() <= quantity && sku.getSkuLever4Count() != 0 && sku.getSkuLever4Price() != 0) {
            return sku.getSkuLever4Price();
        }

        if (sku.getSkuLever3Count() <= quantity && sku.getSkuLever3Count() != 0 && sku.getSkuLever3Price() != 0) {
            return sku.getSkuLever3Price();
        }

        if (sku.getSkuLever2Count() <= quantity && sku.getSkuLever2Count() != 0 && sku.getSkuLever2Price() != 0) {
            return sku.getSkuLever2Price();
        }

        if (sku.getSkuLever1Count() <= quantity && sku.getSkuLever1Count() != 0 && sku.getSkuLever1Price() != 0) {
            return sku.getSkuLever1Price();
        }

        return sku.getPrice();

    }

    /**
     * 添加商品信息
     */
    public void create(Goods goods) {

        Requires.isTrue(goods.getDefaultPrice() > 0, "价格必须大于0");
        Requires.isTrue(goods.getDefaultPrice() <= goods.getMarketPrice(), "市场价不能小于默认价格");

        if (goods.getAttributeChannel() != null && goods.getAttributeChannel().getId() == 0) {
            goods.setAttributeChannel(null);
        }

        if (goods.getFreightTemplate() != null && goods.getFreightTemplate().getId() == 0) {
            goods.setFreightTemplate(null);
        }

        if (goods.getSupplierFreightTemplate() != null && goods.getSupplierFreightTemplate().getId() == 0) {
            goods.setSupplierFreightTemplate(null);
        }

        if (goods.getAffiliatedUnit() != null && goods.getAffiliatedUnit().getId() == 0) {
            goods.setAffiliatedUnit(null);
        }

        if (goods.getUltimateUnit() != null && goods.getUltimateUnit().getId() == 0) {
            goods.setUltimateUnit(null);
        }

        if (goods.getUnit() != null && goods.getUnit().getId() == 0) {
            goods.setUnit(null);
        }

        if (goods.getBrand() != null && goods.getBrand().getId() == 0) {
            goods.setBrand(null);
        }

        if (goods.getSupplierFreightTemplate() != null && goods.getSupplierFreightTemplate().getId() > 0) {
            goods.setSupplierFreightTemplate(goods.getSupplierFreightTemplate());
        }

        goods.setStatus(1);
        goods.setCreateTime(new Timestamp(System.currentTimeMillis()));

        goodsRepository.save(goods);

        builderImages(goods);
        buildSaleAttributes(goods);
        builderSku(goods);
        builderParams(goods);

    }

    /**
     * 编辑商品
     */
    public void modify(Goods params) {

        Requires.isTrue(params.getDefaultPrice() > 0, "价格必须大于0");
        Requires.isTrue(params.getDefaultPrice() <= params.getMarketPrice(), "市场价不能小于默认价格");

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setName(params.getName());
        goods.setGoodsNo(params.getGoodsNo());
        goods.setGoodsChannel(params.getGoodsChannel());
        goods.setDefaultImage(params.getDefaultImage());
        goods.setQualificationImage(params.getQualificationImage());
        goods.setDefaultPrice(params.getDefaultPrice());
        goods.setMarketPrice(params.getMarketPrice());
        goods.setContent(params.getContent());
        goods.setImagesData(params.getImagesData());
        goods.setParamsData(params.getParamsData());
        goods.setSkusData(params.getSkusData());
        goods.setSaleAttributeData(params.getSaleAttributeData());
        goods.setPostage(params.getPostage());
        goods.setPostageType(params.getPostageType());
        goods.setHaveSku(params.getHaveSku());
        goods.setBrand(params.getBrand());
        goods.setSupplierPostage(params.getSupplierPostage());
        goods.setSupplierPostageType(params.getSupplierPostageType());
        goods.setGram(params.getGram());

        goods.setHaveMultiUnit(params.getHaveMultiUnit());
        goods.setUnit(params.getUnit());

        if (params.getAffiliatedUnit() != null && params.getAffiliatedUnit().getId() > 0) {
            goods.setAffiliatedUnit(params.getAffiliatedUnit());
            goods.setAffiliatedUnitValue(params.getAffiliatedUnitValue());
        }

        if (params.getUltimateUnit() != null && params.getUltimateUnit().getId() > 0) {
            goods.setUltimateUnit(params.getUltimateUnit());
            goods.setUltimateUnitValue(params.getUltimateUnitValue());
        }

        if (params.getAttributeChannel() != null && params.getAttributeChannel().getId() > 0) {
            goods.setAttributeChannel(params.getAttributeChannel());
        }

        if (params.getFreightTemplate() != null && params.getFreightTemplate().getId() > 0) {
            goods.setFreightTemplate(params.getFreightTemplate());
        }

        if (params.getSupplierFreightTemplate() != null && params.getSupplierFreightTemplate().getId() > 0) {
            goods.setSupplierFreightTemplate(params.getSupplierFreightTemplate());
        }

        if (goods.getBrand().getId() == 0) {
            goods.setBrand(null);
        }

        goodsRepository.save(goods);

        removeImages(goods);
        removeSaleAttributes(goods);
        removeSku(goods);
        removeParams(goods);

        builderImages(goods);
        buildSaleAttributes(goods);
        builderSku(goods);
        builderParams(goods);

    }


    /**
     * 保存商品参数组合 （如：保质期：3年）
     */
    private void builderParams(Goods goods) {
        if (Strings.isNullOrEmpty(goods.getParamsData())) {
            return;
        }
        JSONArray paramsJsonArray = JSON.parseArray(goods.getParamsData());
        for (Object o : paramsJsonArray) {
            GoodsParams params = JSON.toJavaObject((JSONObject) o, GoodsParams.class);
            params.setGoods(goods);
            params.setMerchant(goods.getMerchant());
            paramsRepository.save(params);
        }
    }

    /**
     * 删除商品参数组合
     */
    private void removeParams(Goods goods) {
        if (CollectionUtils.isNotEmpty(goods.getParamses())) {
            paramsRepository.delete(goods.getParamses());
        }
    }

    /**
     * 保存商品SKU组合
     */
    private void builderSku(Goods goods) {

        if (Strings.isNullOrEmpty(goods.getSkusData())) {
            return;
        }

        int store = 0;

        JSONArray skuJsonArray = JSON.parseArray(goods.getSkusData());
        for (Object o : skuJsonArray) {
            GoodsSku sku = JSON.toJavaObject((JSONObject) o, GoodsSku.class);
            sku.setGoods(goods);
            sku.setMerchant(goods.getMerchant());

            List<String> list = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(sku.getSkuNo());
            List<String> skuNames = new ArrayList<>(list.size());

            for (int i = 0; i < list.size(); i++) {
                GoodsAttribute goodsAttribute = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(Long.parseLong(list.get(i))), GoodsAttribute.class);
                Requires.notNull(goodsAttribute, "属性" + list.get(i) + "不存在");
                skuNames.add(goodsAttribute.getName());
                if (i == 0) {
                    sku.setAttribute1(goodsAttribute);
                } else if (i == 1) {
                    sku.setAttribute2(goodsAttribute);
                } else if (i == 2) {
                    sku.setAttribute3(goodsAttribute);
                } else if (i == 3) {
                    sku.setAttribute4(goodsAttribute);
                } else if (i == 4) {
                    sku.setAttribute5(goodsAttribute);
                }
            }
            sku.setSkuNames(String.join(",", skuNames));
            Requires.isTrue(sku.getStore() > 0, "库存必须大于0");
            Requires.isTrue(sku.getPrice() > 0, "价格必须大于0");
            skuRepository.save(sku);
            store += sku.getStore();
        }

        goods.setStore(store);
        goodsRepository.save(goods);
    }

    /**
     * 删除SKU组合
     */
    private void removeSku(Goods goods) {
        if (CollectionUtils.isNotEmpty(goods.getSkus())) {
            skuRepository.delete(goods.getSkus());
        }
    }

    /**
     * 保存商品销售规格
     */
    private void buildSaleAttributes(Goods goods) {

        if (Strings.isNullOrEmpty(goods.getSaleAttributeData())) {
            return;
        }

        for (String item : Splitter.on(";").omitEmptyStrings().trimResults().splitToList(goods.getSaleAttributeData())) {

            String parentId = item.substring(0, item.indexOf(":"));
            if (!NumberUtils.isNumber(parentId)) {
                continue;
            }

            GoodsAttribute parentAttribute = queryChannelService.findOne(GoodsAttribute.class, Long.parseLong(parentId));

            GoodsSaleAttribute saleAttribute = new GoodsSaleAttribute();
            saleAttribute.setGoods(goods);
            saleAttribute.setMerchant(goods.getMerchant());
            saleAttribute.setName(parentAttribute.getName());
            saleAttribute.setAttributeId(parentAttribute.getId());
            saleAttribute.setCreateTime(new Timestamp(System.currentTimeMillis()));
            saleAttributeRepository.save(saleAttribute);

            for (String id : Splitter.on("-").splitToList(item.substring(item.indexOf(":") + 1))) {
                GoodsAttribute valueAttribute = queryChannelService.findOne(GoodsAttribute.class, Long.parseLong(id));

                GoodsSaleAttribute chilrenSaleAttribute = new GoodsSaleAttribute();
                chilrenSaleAttribute.setMerchant(goods.getMerchant());
                chilrenSaleAttribute.setParent(saleAttribute);
                chilrenSaleAttribute.setName(valueAttribute.getName());
                chilrenSaleAttribute.setAttributeId(valueAttribute.getId());
                chilrenSaleAttribute.setCreateTime(new Timestamp(System.currentTimeMillis()));
                saleAttributeRepository.save(chilrenSaleAttribute);
            }
        }
    }

    /**
     * 删除销售规格组合
     */
    private void removeSaleAttributes(Goods goods) {

        for (GoodsSaleAttribute item : goods.getSaleAttributes()) {
            saleAttributeRepository.delete(item.getValues());
            saleAttributeRepository.delete(item);
        }

    }

    /**
     * 保存商品相册
     */
    private void builderImages(Goods goods) {
        List<String> images = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(goods.getImagesData());
        for (String name : images) {
            GoodsImage image = new GoodsImage();
            image.setName(name);
            image.setGoods(goods);
            image.setMerchant(goods.getMerchant());
            image.setCreateTime(new Timestamp(System.currentTimeMillis()));
            imageRepository.save(image);
        }
    }

    /**
     * 删除商品相册
     */
    private void removeImages(Goods goods) {
        if (CollectionUtils.isNotEmpty(goods.getImages())) {
            imageRepository.delete(goods.getImages());
        }
    }

    /**
     * 删除商品（逻辑删除）
     */
    public void remove(Goods goods) {
        goods.setStatus(7);
        goodsRepository.save(goods);
    }

    /**
     * 申请上架
     */
    public void applyPutaway(Goods goods) {
        goods.setStatus(2);
        goods.setApplyTime(new Timestamp(System.currentTimeMillis()));
        goodsRepository.save(goods);
    }

    /**
     * 审核商品
     */
    public void check(Goods params) {

        if (params.getStatus() == 4) {
            Requires.hasLength(params.getCheckNote(), "备注不能为空");
        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setStatus(params.getStatus());
        goods.setCheckTime(new Timestamp(System.currentTimeMillis()));
        goods.setCheckNote(params.getCheckNote());
        goodsRepository.save(goods);

        if (goods.getStatus() == 3) {
            WebUser merchant = goods.getMerchant();
            merchant.setGoodsNumber(merchant.getGoodsNumber() + 1);
            userRepository.save(merchant);
        }


    }

    /**
     * 推荐商品到首页
     */
    public void recommend(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setRecommend(params.isRecommend());
        goods.setRecommendTime(new Timestamp(System.currentTimeMillis()));
        goodsRepository.save(goods);

    }

    /**
     * 批量推荐到首页
     */
    public void allRecommend(List<Goods> goodses) {
        for (Goods goodse : goodses) {
            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(goodse.getId()), Goods.class);
            goods.setRecommend(true);
            goods.setRecommendTime(new Timestamp(System.currentTimeMillis()));
            goodsRepository.save(goods);
        }
    }

    /**
     * 批量取消推荐到首页
     */
    public void allUnRecommend(List<Goods> goodses) {
        for (Goods goodse : goodses) {
            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(goodse.getId()), Goods.class);
            goods.setRecommend(false);
            goodsRepository.save(goods);
        }
    }

    /**
     * 下架
     */
    public void soldout(Goods goods) {
        goods.setStatus(5);
        goodsRepository.save(goods);
    }


    /**
     * 批量申请上架
     */
    public void applysPutaway(List<Goods> goodss) {

        for (Goods goods : goodss) {
            applyPutaway(goods);
        }

    }

    /**
     * 批量下架商品
     */
    public void soldoutss(List<Goods> transform) {
        for (Goods goods : transform) {
            soldout(goods);
        }
    }

    /**
     * 批量审核通过，批量上架销售
     */
    public void allPass(List<Goods> transform) {
        for (Goods goods : transform) {

            goods.setStatus(3);
            goods.setCheckTime(new Timestamp(System.currentTimeMillis()));
            goodsRepository.save(goods);

            WebUser merchant = goods.getMerchant();
            merchant.setGoodsNumber(merchant.getGoodsNumber() + 1);
            userRepository.save(merchant);

        }
    }

    /**
     * 批量审核不通过
     */
    public void allNotPass(List<Goods> transform, String note) {
        Requires.hasLength(note, "备注不能为空");
        for (Goods goods : transform) {
            goods.setStatus(4);
            goods.setCheckNote(note);
            goods.setCheckTime(new Timestamp(System.currentTimeMillis()));
            goodsRepository.save(goods);
        }
    }


    /**
     * 编辑商品基本信息
     */
    public void modifyInfo(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setName(params.getName());
        goods.setGoodsNo(params.getGoodsNo());
        goods.setGoodsChannel(params.getGoodsChannel());
        goods.setDefaultImage(params.getDefaultImage());
        goods.setQualificationImage(params.getQualificationImage());
        goods.setDefaultPrice(params.getDefaultPrice());
        goods.setMarketPrice(params.getMarketPrice());
        goods.setContent(params.getContent());
        goods.setImagesData(params.getImagesData());
        goods.setParamsData(params.getParamsData());
        //        goods.setSkusData(params.getSkusData());
        //        goods.setSaleAttributeData(params.getSaleAttributeData());
        goods.setPostage(params.getPostage());
        goods.setPostageType(params.getPostageType());
        goods.setGram(params.getGram());


        if (params.getFreightTemplate().getId() > 0) {
            goods.setFreightTemplate(params.getFreightTemplate());
        }

        goodsRepository.save(goods);

        removeImages(goods);
        //        removeSaleAttributes(goods);
        //        removeSku(goods);
        removeParams(goods);

        builderImages(goods);
        //        buildSaleAttributes(goods);
        //        builderSku(goods);
        builderParams(goods);
    }


    /**
     * 修改库存
     */
    public void modifyStore(String data) {
        List<String> datas = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data);

        int stores = 0;
        long id = 0;

        for (String item : datas) {
            String idStr = item.substring(0, item.indexOf("-"));
            String storeStr = item.substring(item.indexOf("-") + 1, item.indexOf(":"));
            String priceStr = item.substring(item.indexOf(":") + 1);

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(Long.parseLong(idStr)), GoodsSku.class);
            sku.setStore(Integer.parseInt(storeStr));
            sku.setPrice(Double.parseDouble(priceStr));
            skuRepository.save(sku);

            id = sku.getGoods().getId();
            stores = stores + sku.getStore();
        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        goods.setStore(stores);

        if (stores == 0) {
            goods.setStatus(6);
        }

        if (stores > 0 && goods.getStatus() == 6) {
            goods.setStatus(3);
        }

        goodsRepository.save(goods);

    }

    /**
     * 采购端商家编辑商品库存与价格
     */
    public void modifyStore(List<GoodsSku> data) {
        int stores = 0;
        long id = 0;

        for (GoodsSku item : data) {

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(item.getId()), GoodsSku.class);
            sku.setStore(item.getStore());
            sku.setPrice(item.getPrice());
            skuRepository.save(sku);

            stores = stores + sku.getStore();

            if (id == 0) {
                id = sku.getGoods().getId();
            }
        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);
        goods.setStore(stores);

        if (stores == 0) {
            goods.setStatus(6);
        }

        if (stores > 0 && goods.getStatus() == 6) {
            goods.setStatus(3);
        }

        goodsRepository.save(goods);

    }

    /**
     * 采购端商家编辑一键代发价格
     */
    public void modifyIssuing(List<GoodsSku> data) {

        for (GoodsSku item : data) {

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(item.getId()), GoodsSku.class);
            sku.setPrice(item.getPrice());
            skuRepository.save(sku);

        }

    }

    /**
     * 设置商品为特价商品，并设置特价活动规则
     */
    public void createBargainStore(Goods params) {
        List<String> datas = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getSkusData());

        int stores = 0;

        for (String item : datas) {
            String idStr = item.substring(0, item.indexOf("-"));
            String storeStr = item.substring(item.indexOf("-") + 1, item.indexOf(":"));
            String priceStr = item.substring(item.indexOf(":") + 1);

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(Long.parseLong(idStr)), GoodsSku.class);
            sku.setBargainStore(Integer.parseInt(storeStr));
            sku.setBargainPrice(Double.parseDouble(priceStr));
            skuRepository.save(sku);

            stores = stores + sku.getBargainStore();
        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setBargainStore(stores);
        goods.setMarketingType(1);
        goods.setBeginDateOfValidity(params.getBeginDateOfValidity());
        goods.setEndDateOfValidity(params.getEndDateOfValidity());
        goods.setBargainPrice(params.getBargainPrice());
        goods.setBargainStatus(1);
        goods.setBargainSalesVolume(0);

        goodsRepository.save(goods);
    }

    /**
     * 特价商品提交审核
     */
    public void applyProcessBargain(Goods goods) {
        goods.setBargainStatus(2);
        goodsRepository.save(goods);
    }

    /**
     * 特价商品审核
     */
    public void bargainProcess(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setBargainStatus(params.getBargainStatus());
        goods.setCheckNote(params.getCheckNote());

        if (params.getBargainStatus() == 3 && DateUtil.parse(goods.getBeginDateOfValidity(), DatePattern.NORM_DATETIME_MINUTE_FORMAT).getTime() <= System.currentTimeMillis()) {
            goods.setBargainStatus(5);
        }

        goodsRepository.save(goods);


    }

    /**
     * 下架特价商品
     */
    public void soldoutBargain(Goods goods) {
        goods.setBargainStatus(7);
        goodsRepository.save(goods);
    }

    /**
     * 当前商品所参与的营销活动（特价、秒杀、拼团、预售）
     * 0、普通商品
     * 1、特价活动商品（预告）
     * 2、特价活动商品（已开始）
     * 3、秒杀活动商品（预告）
     * 4、秒杀活动商品（已开始）
     * 5、拼团活动商品
     * 6、预售活动商品
     */
    public int ensureMarketingType(Goods goods) {

        int defaultType = 0;

        if (goods.getMarketingType() == 1 && goods.getBargainStatus() == 3) {
            return 1;
        }

        if (goods.getMarketingType() == 1 && goods.getBargainStatus() == 5) {
            return 2;
        }

        if (goods.getMarketingType() == 2 && goods.getSeckillStatus() == 3) {
            return 3;
        }

        if (goods.getMarketingType() == 2 && goods.getSeckillStatus() == 5) {
            return 4;
        }

        return defaultType;
    }

    /**
     * 添加预售商品
     */
    public void addPresellGoods(Goods params) {

        List<String> datas = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getSkusData());

        for (String item : datas) {
            long id = Long.parseLong(item.substring(0, item.indexOf(":")));
            double presellPrice = Double.parseDouble(item.substring(item.indexOf(":") + 1, item.indexOf("-")));
            double presellSubscription = Double.parseDouble(item.substring(item.indexOf("-") + 1, item.lastIndexOf("-")));
            double presellDeduction = Double.parseDouble(item.substring(item.lastIndexOf("-") + 1));

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(id), GoodsSku.class);
            sku.setPresellPrice(presellPrice);
            sku.setPresellDeduction(presellDeduction);
            sku.setPresellSubscription(presellSubscription);
            sku.setPresellRetainage(ArithUtils.sub(ArithUtils.sub(presellPrice, presellSubscription), presellDeduction));

            skuRepository.save(sku);

        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setMarketingType(3);
        goods.setPresellSubscriptionPayBeginTime(params.getPresellSubscriptionPayBeginTime());
        goods.setPresellSubscriptionPayEndTime(params.getPresellSubscriptionPayEndTime());
        goods.setPresellRetainagePayBeginTime(params.getPresellRetainagePayBeginTime());
        goods.setPresellRetainagePayEndTime(params.getPresellRetainagePayEndTime());
        goods.setPresellStatus(1);
        goods.setPresellPrice(params.getPresellPrice());

        goodsRepository.save(goods);

    }

    /**
     * 提交预售审核申请
     */
    public void applyProcessPresell(Goods goods) {

        goods.setPresellStatus(2);
        goodsRepository.save(goods);

    }

    /**
     * 下架预售
     */
    public void soldoutPresell(Goods goods) {
        goods.setPresellStatus(9);
        goodsRepository.save(goods);
    }

    /**
     * 预售审核
     */
    public void presellProcess(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setPresellStatus(params.getPresellStatus());
        goods.setCheckNote(params.getCheckNote());
        goodsRepository.save(goods);
    }

    /**
     * 添加拼团活动商品
     */
    public void addGroupBookingGoods(Goods params) {
        List<String> datas = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(params.getSkusData());

        int store = 0;

        for (String item : datas) {
            long id = Long.parseLong(item.substring(0, item.indexOf(":")));
            double groupBookingPrice = Double.parseDouble(item.substring(item.indexOf(":") + 1, item.indexOf("-")));
            int groupBookingStore = Integer.parseInt(item.substring(item.indexOf("-") + 1));

            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(id), GoodsSku.class);
            sku.setGroupBookingPrice(groupBookingPrice);
            sku.setGroupBookingStore(groupBookingStore);

            skuRepository.save(sku);

            store += sku.getGroupBookingStore();

        }

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setMarketingType(4);
        goods.setGroupBookingBeginTime(params.getGroupBookingBeginTime());
        goods.setGroupBookingEndTime(params.getGroupBookingEndTime());
        goods.setGroupBookingCondition(params.getGroupBookingCondition());
        goods.setGroupBookingLimit(params.getGroupBookingLimit());
        goods.setGroupBookingPrice(params.getGroupBookingPrice());
        goods.setGroupBookingStatus(1);
        goods.setGroupBookingStore(store);
        goods.setGroupBookingSalesVolume(0);

        goodsRepository.save(goods);
    }

    /**
     * 提交拼团审核
     */
    public void applyProcessGroupBooking(Goods goods) {
        goods.setGroupBookingStatus(2);
        goodsRepository.save(goods);
    }

    /**
     * 下架拼团商品
     */
    public void soldoutGroupBooking(Goods goods) {
        goods.setGroupBookingStatus(7);
        goodsRepository.save(goods);
    }

    /**
     * 拼团审核
     */
    public void groupBookingProcess(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setGroupBookingStatus(params.getGroupBookingStatus());
        goods.setCheckNote(params.getCheckNote());
        goodsRepository.save(goods);
    }

    /**
     * 删除特价活动
     */
    public void removeBargain(Goods params) {

        Goods goods = queryChannelService.findOne(QGoods.goods.eq(params), Goods.class);
        goods.setMarketingType(0);
        goodsRepository.save(goods);

    }

    /**
     * 删除预售活动
     */
    public void removePresell(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.eq(params), Goods.class);
        goods.setMarketingType(0);
        goodsRepository.save(goods);
    }

    /**
     * 删除拼团活动
     */
    public void removeGroupBooking(Goods params) {

        Goods goods = queryChannelService.findOne(QGoods.goods.eq(params), Goods.class);
        goods.setMarketingType(0);
        goodsRepository.save(goods);

    }

    /**
     * 是否推荐到采购端首页
     */
    public void recommendSupplier(Goods params) {
        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(params.getId()), Goods.class);
        goods.setRecommendSupplier(params.isRecommendSupplier());
        goodsRepository.save(goods);
    }

    /**
     * 一键代发
     */
    public Goods issuing(Goods goods, List<GoodsSku> details) {

        List<GoodsImage> images = goods.getImages();
        //        List<GoodsSku> skus = goods.getSkus();
        List<GoodsSaleAttribute> saleAttributes = goods.getSaleAttributes();

        goods.setImages(null);
        goods.setSkus(null);
        goods.setSaleAttributes(null);
        goods.setParamses(null);
        goods.setId(0);
        goods.setIsIssuingType(1);
        goods.setCreateTime(new Timestamp(System.currentTimeMillis()));
        goods.setIsSupplier(0);
        goods.setRecommendSupplier(false);
        goods.setRecommend(false);

        goodsRepository.save(goods);

        for (GoodsImage item : images) {
            GoodsImage image = new GoodsImage();
            image.setCreateTime(item.getCreateTime());
            image.setGoods(goods);
            image.setMerchant(goods.getMerchant());
            image.setName(item.getName());
            imageRepository.save(image);
        }


        for (GoodsSaleAttribute item : saleAttributes) {

            GoodsAttribute oldAttr = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(item.getAttributeId()), GoodsAttribute.class);

            GoodsAttribute attr = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(oldAttr.getId()), GoodsAttribute.class);

            if (null == attr) {
                attr = new GoodsAttribute();
                BeanUtils.copyProperties(oldAttr, attr);
                attr.setId(0);
                attr.setType(2);
                attr.setStatus(2);
                attr.setMerchant(goods.getMerchant());
                attr.setAttributes(null);
                attr.setIssuingSupplierAttributeId(oldAttr.getId());
                attributeRepository.save(attr);
            }


            GoodsSaleAttribute attribute = new GoodsSaleAttribute();
            attribute.setGoods(goods);
            attribute.setMerchant(goods.getMerchant());
            attribute.setCreateTime(item.getCreateTime());
            attribute.setAttributeId(attr.getId());
            attribute.setName(attr.getName());
            saleAttributeRepository.save(attribute);

            for (GoodsSaleAttribute childrenItem : item.getValues()) {

                GoodsAttribute oldAttr2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(childrenItem.getAttributeId()), GoodsAttribute.class);

                GoodsAttribute attr2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(oldAttr2.getId()), GoodsAttribute.class);

                if (null == attr2) {
                    attr2 = new GoodsAttribute();
                    BeanUtils.copyProperties(oldAttr2, attr2);
                    attr2.setId(0);
                    attr2.setType(2);
                    attr2.setStatus(2);
                    attr2.setParent(attr);
                    attr2.setMerchant(goods.getMerchant());
                    attr2.setAttributes(null);
                    attr2.setIssuingSupplierAttributeId(oldAttr2.getId());
                    attributeRepository.save(attr2);
                }

                GoodsSaleAttribute saleAttribute = new GoodsSaleAttribute();
                saleAttribute.setMerchant(childrenItem.getMerchant());
                saleAttribute.setCreateTime(childrenItem.getCreateTime());
                saleAttribute.setAttributeId(attr2.getId());
                saleAttribute.setName(attr2.getName());
                saleAttribute.setParent(attribute);
                saleAttributeRepository.save(saleAttribute);

            }


        }

        for (GoodsSku detail : details) {
            GoodsSku sku = new GoodsSku();
            sku.setGoods(goods);
            sku.setMerchant(goods.getMerchant());
            sku.setCode(detail.getCode());
            sku.setSkuNames(detail.getSkuNames());
            sku.setStore(detail.getStore());
            sku.setPrice(detail.getPrice());
            sku.setIssuingPrice(detail.getIssuingPrice());


            GoodsAttribute attribute1 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(detail.getAttribute1().getId()), GoodsAttribute.class);
            sku.setAttribute1(attribute1);
            sku.setSkuNo(attribute1.getId() + "");

            if (detail.getAttribute2() != null) {
                GoodsAttribute attribute2 = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.issuingSupplierAttributeId.eq(detail.getAttribute2().getId()), GoodsAttribute.class);
                sku.setAttribute2(attribute2);
                sku.setSkuNo(attribute1.getId() + "-" + attribute2.getId());
            }

            skuRepository.save(sku);
        }

        return goods;

    }


    /**
     * 拼团活动 - 批量审核成功
     */
    public void allApplyCheck(String data) {
        List<Long> ids = Lists.newArrayList();
        if (data.contains(";")) {
            ids = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(data).stream().map(Long::parseLong).collect(Collectors.toList());
        } else {
            ids.add(NumberUtils.toLong(data));
        }
        List<Goods> topics = queryChannelService.findAll(QGoods.goods.id.in(ids), Goods.class);
        for (Goods goods : topics) {
            applyProcessGroupBooking(goods);
        }
    }
}
